﻿using Metabase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ApplicationGUI
{
    public class MetabaseConnector
    {
        // Процедура подключения к репозиторию
        static public MetabaseHandler ConnectionToMetabase()
        {
            MetabaseHandler metabaseHandler = null;
            RepositoryListForm repoListForm = new RepositoryListForm();
            if (repoListForm.ShowDialog() == DialogResult.OK)
            {
                metabaseHandler = repoListForm.MetabaseHandler;
                bool connResult = metabaseHandler.dbHandler.Connect();
                if (!connResult)
                {
                    MessageBox.Show(metabaseHandler.dbHandler.connectException.Message, AppResources.ErrorHeader, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    metabaseHandler = null;
                }
                else
                {
                    try
                    {
                        metabaseHandler.InitMetabase();
                        if (!repoListForm.MetabaseHandler.MetabaseExists) // Если репозитория нет
                        {
                            // Спросим о его создании
                            DialogResult dialogResult = MessageBox.Show(AppResources.QuestionCreateRepository, AppResources.Confirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                            if (dialogResult == DialogResult.Yes)
                            {
                                // Создадим
                                repoListForm.CheckAndCreateMetabase(repoListForm.MetabaseHandler.dbHandler, repoListForm.MetabaseHandler.MetabaseName);
                            }
                            //metabaseHandler = null;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(AppResources.MetabaseCreateError + ": " + ex.Message, AppResources.ErrorHeader, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        metabaseHandler = null;
                    }
                }
            }
            else
            {
                metabaseHandler = null;
            }
            return metabaseHandler;
        }
    }
}
